<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>路由history模式简单版本</title>
</head>
<body>
    <ul>
      <li><a href="/">go to one</a></li>
      <li><a href="/two">go to two</a></li>
      <li><a href="/three">go to three</a></li>
    </ul>
    <div id="app"></div>

    <script>
      // 路由视图
      var app = document.querySelector('#app');

      // 路有变化时对应UI
      function onPopState() {
        switch(location.pathname) {
          case '/':
            app.innerHTML = '我是one页面';
            break;
          case '/two':
            app.innerHTML = '我是two页面';
            break;
          case '/three':
            app.innerHTML = '我是three页面';
            break;
          default: 
            app.innerHTML = '我是one页面';
            break;
        }
      }

      var links = document.querySelectorAll('a');
      links.forEach(el => {
        el.onclick = function(e){
          // 阻止a标签默认事件
          e.preventDefault();
          history.pushState(null, '', el.getAttribute('href'))
          onPopState()
        }
      });

      // 页面加载完不会触发 hashchange，这里主动触发一次 hashchange 事件
      window.addEventListener('load', onPopState, false);
      // 监听路由变化
      window.addEventListener('popstate', onPopState, false);

    </script>
</body>
</html>